package corbaEventService;

import java.util.UUID;

import org.omg.CORBA.Any;
import org.omg.CORBA.BooleanHolder;
import org.omg.CORBA.Object;
import org.omg.PortableServer.POAPackage.ServantNotActive;
import org.omg.PortableServer.POAPackage.WrongPolicy;

import cosEventChannelAdmin.EventChannel;
import cosEventComm.Disconnected;
import cosEventComm.PullSupplier;
import cosEventComm.PullSupplierHelper;
import cosEventComm.PullSupplierPOA;


public class PullSupplierImpl extends PullSupplierPOA {
	private EventChannel channel;	
	private String id;
	
	public PullSupplierImpl(EventChannel channel) {
		super();
		this.channel = channel;
		id = UUID.randomUUID().toString();
	}

	@Override
	public Any pull() throws Disconnected {
		BooleanHolder has_event = new BooleanHolder();
		Any any;
		do{
			any = channel.try_pull(id, has_event);
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}while(!has_event.value);
		return any;
	}

	@Override
	public Any try_pull(BooleanHolder has_event) throws Disconnected {
		has_event.value = false;		
		return channel.try_pull(id, has_event);
	}

	@Override
	public void disconnect_pull_supplier() {
		Object ref = null;
		try {
			ref = _poa().servant_to_reference(this);
		} catch (ServantNotActive e) {				
			e.printStackTrace();
		} catch (WrongPolicy e) {				
			e.printStackTrace();
		}
		PullSupplier consumer = PullSupplierHelper.narrow(ref);
		channel.disconnect_pull_supplier(consumer);
	}

	@Override
	public String getID() {
		return id;
	}

}
